package com.tanhua.server.serivce;

import cn.hutool.core.collection.CollUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SmallVideosService {

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发布端视频
     *  videoThumbnail：图片（上传到阿里云oss）
     *  videoFile：视频（上传到FastDFS）
     */
    //@CacheEvict(value = "videos",allEntries = true)
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1、图片上传到阿里云oss
        String picUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(),
                videoThumbnail.getInputStream());
        //2、视频上传到FastDFS
        String filename = videoFile.getOriginalFilename();  //1.jpg
        filename = filename.substring(filename.lastIndexOf(".")+1); //jpg
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);//输入流，文件大小，文件的后缀名，元数据（null）
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //3、创建Video对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(picUrl);
        video.setVideoUrl(videoUrl);
        video.setCreated(System.currentTimeMillis());
        video.setText("我就是我，是颜色不一样的烟火"); //心情文字，前端未实现。配置默认值
        //4、调用API保存
        videoApi.save(video);
    }

    /**
     * 缓存的效果
     *     videos::userid_page_pagesize
     *
     *
     */
    //@Cacheable(value = "videos",key="T(com.tanhua.server.interceptor.UserHolder).userId+
    // '_'+#page+'_'+#pagesize")
    //查询视频列表（推荐和数据库）
    public PageResult findVideos(Integer page, Integer pagesize) {
        //1、从redis中查询推荐数据
        String key = Constants.VIDEOS_RECOMMEND+UserHolder.getUserId();
        String value = redisTemplate.opsForValue().get(key);
        List<Video> list = new ArrayList<>();
        if(StringUtils.isEmpty(value)) {
            //2、如果推荐数据不存在，查询数据库表，分页展示
            list = videoApi.findAll(page,pagesize);
        }else {
            //3、如果推荐数据存在，分页查询视频获取推荐列表  List<Video>
            String[] videsIds = value.split(",");
            list = videoApi.findByIds(videsIds,page,pagesize);
        }
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //4、一个 List<Video>构造一个List<VideoVo>
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            //视频发布人的用户详情
            Long userId = video.getUserId();
            UserInfo userInfo = map.get(userId);
            VideoVo vo = VideoVo.init(userInfo, video);
            vos.add(vo);
        }
        //5、构造返回值
        return new PageResult(page,pagesize,0l,vos);
    }

    @Autowired
    private MqMessageService messageService;

    //视频点赞
    public void like(String videoId) {
        messageService.sendLogService(UserHolder.getUserId(),"0302","video",videoId);
    }
}
